# Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd.
# SPDX-License-Identifier: MulanPSL-2.0
import os
from agent.common.config import Config
from agent.common.system import sysCommand


def _test(param_list, domain):
    try:
        _domain = domain()
    except Exception as e:
        print("[-] load domain {} failed: {}".format(domain, e))
    else:
        res = _domain.Backup(param_list)
        print("[+] backup result:{}".format(res))
        res = _domain.BackupAll()
        print("[+] backup all result:{}".format(res))
        res = _domain.SetParam(param_list)
        print("[+] set result:{}".format(res))
        res = _domain.GetParam(param_list)
        print("[+] get result:{}".format(res))
        res = _domain.Rollback(all_param = False)
        print("[+] rollback result:{}".format(res))
        res = _domain.Rollback(all_param = True)
        print("[+] rollback all result:{}".format(res))

def _create_file(script_path, dest_path):
    if not os.path.exists(dest_path):
        os.makedirs(dest_path)
    sysCommand("cp {} {}".format(script_path, dest_path))

def test_audio():
    from agent.domain.audio import Audio
    param_list = {
        "timeout":{"value": 10}
    }
    _test(param_list, Audio)

def test_cpu():
    from agent.domain.cpu import Cpu 
    param_list = {
        "governor":{"value":"performance"},
        "energy_perf_bias":{"value":"performance"},
        "min_perf_pct":{"value":100},
        "force_latency":{"value":"cstate.id:1"},
    }
    _test(param_list, Cpu)

    param_list = {
        "force_latency":{"value":99},
        "governor":{"value":"conservative|powersave"},
        "energy_perf_bias":{"value":"normal"},
    }
    _test(param_list, Cpu)

    param_list = {
        "force_latency":{"value":"cstate.id_no_zero:1|3"},
        "governor":{"value":"ondemand|powersave"},
        "energy_perf_bias":{"value":"powersave|power"},
    }
    _test(param_list, Cpu)

def test_disk():
    from agent.domain.disk import Disk
    param_list = {
        "readahead":{"value": "4096"},
        "apm":{"value":128},
        "spindown":{"value":6},
    }
    _test(param_list, Disk)

def test_env():
    from agent.domain.env import Env
    param_list = {
        "cpu-partitioning": {"value": "start"},
        "realtime": {"value": "start"}
    }
    _test(param_list, Env)

def test_fio():
    from agent.domain.fio import Fio
    param_list = {
        "iodepth": {"value": "1"},
        "bs": {"value": "512B"},
        "numjobs": {"value": 4}
    }
    script_path = "/etc/keentune/keentuned/benchmark/fio/fio_IOPS_base.py"
    dest_path = os.path.join(Config.BENCKMARK_FIlE, "benchmark/fio")
    _create_file(script_path, dest_path)
    _test(param_list, Fio)

def test_iperf():
    from agent.domain.iperf import Iperf
    param_list = {
        "Parallel": {"value": 1},
        "window_size": {"value": 10240},
        "length_buffers": {"value": 10240}
    }
    script_path = "/etc/keentune/keentuned/benchmark/iperf/iperf.py"
    dest_path = os.path.join(Config.BENCKMARK_FIlE, "benchmark/iperf")
    _create_file(script_path, dest_path)
    _test(param_list, Iperf)

def test_irqbalance():
    from agent.domain.irqbalance import Irqbalance
    param_list = {
        "banned_cpus": {"value": 5}
    }
    _test(param_list, Irqbalance)

def test_kernel_mem():
    from agent.domain.kernel_mem import KernelMem
    param_list = {
        "code_hugepage": {"value": 1}
    }
    _test(param_list, KernelMem)

def test_limits():
    from agent.domain.limits import Limits
    param_list = {
        "hard_nofile": {"value": 1048576},
        "soft_nofile": {"value": 1048576},
        "ulimit": {"value": 1048576},
        "file-max": {"value": 1048576}
    }
    _test(param_list, Limits)

def test_my_cnf():
    from agent.domain.my_cnf import MyCnf
    param_list = {
        "max_connections": {"value": 10000},
        "key_buffer_size": {"value": 21474836},
        "skip_ssl": {"value": "SET_TRUE"},
        "innodb_table_locks": {"value": "ON"}
    }
    _test(param_list, MyCnf)

def test_net():
    from agent.domain.net import Net
    param_list = {
        "XPS":{"value":"different"},
        "RPS":{"value":"different"},
        "smp_affinity":{"value":"dedicated"},
        "nf_conntrack_hashsize":{"value":"1048576"},
    }
    _test(param_list, Net)

def test_nginx_conf():
    from agent.domain.nginx_conf import NginxConf
    param_list = {
        "worker_connections":{"value":10240},
        "multi_accept":{"value":"on"},
        "open_file_cache":{"value":"max=10240 inactive=10s"},
        "ssl_buffer_size":{"value":"256k"},
    }
    _test(param_list, NginxConf)

def test_scheduler():
    """
    accelerator-performance.conf
    sched_min_granularity_ns = 10000000

    mysql.conf
    sched_latency_ns=60000000
    sched_migration_cost_ns=500000
    sched_min_granularity_ns=15000000
    sched_wakeup_granularity_ns=2000000

    postgresql.conf
    sched_min_granularity_ns = 10000000
    """
    from agent.domain.scheduler import Scheduler
    param_list = {
        "sched_min_granularity_ns":{"value":10000000},
        "sched_latency_ns":{"value":60000000},
        "sched_migration_cost_ns":{"value":500000},
        "sched_wakeup_granularity_ns":{"value":2000000},
    }
    _test(param_list, Scheduler)

def test_scsi_host():
    from agent.domain.scsi_host import ScsiHost
    param_list = {
        "alpm":{"value":"medium_power"}
    }
    _test(param_list, ScsiHost)

def test_sysbench():
    from agent.domain.sysbench import Sysbench
    param_list = {
        "tables": {"value": 3},
        "threads": {"value": 3},
        "table-size": {"value": 100000},
        "thread-stack-size": {"value": 32768}
    }
    script_path = "/etc/keentune/keentuned/benchmark/sysbench/sysbench_mysql_read_write.py"
    dest_path = os.path.join(Config.BENCKMARK_FIlE, "benchmark/sysbench")
    _create_file(script_path, dest_path)
    _test(param_list, Sysbench)

def test_sysctl():
    from agent.domain.sysctl import Sysctl
    param_list = {
        "fs.aio-max-nr": {"value": 102400},
        "fs.file-max": {"value": 102400},
        "kernel.dmesg_restrict": {"value": "0"},
        "kernel.sched_migration_cost_ns": {"value": 5000}
    }
    _test(param_list, Sysctl)

def test_sysfs():
    from agent.domain.sysfs import Sysfs
    param_list = {
        "/sys/bus/workqueue/devices/writeback/cpumask": {"value": "000000df"},
        "/sys/devices/system/machinecheck/machinecheck*/ignore_ce": {"value": 1},
        "/sys/devices/virtual/workqueue/*/cpumask": {"value": "000000df"},
        "/sys/devices/virtual/workqueue/cpumask": {"value": "000000df"}
    }
    _test(param_list, Sysfs)

def test_systemd():
    from agent.domain.systemd import Systemd
    param_list = {
        "cpu_affinity": {"value": "0,1,2,3,4,6,7"}
    }
    _test(param_list, Systemd)

def test_vm():
    from agent.domain.vm import Vm
    param_list = {
        "transparent_hugepages": {"value": "never"}
    }
    _test(param_list, Vm)

def test_wrk():
    from agent.domain.wrk import Wrk
    param_list = {
        "threads": {"value": 2},
        "connections": {"value": 10}
    }
    script_path = "/etc/keentune/keentuned/benchmark/wrk/wrk_parameter_tuning.py"
    dest_path = os.path.join(Config.BENCKMARK_FIlE, "benchmark/wrk")
    _create_file(script_path, dest_path)
    _test(param_list, Wrk)


if __name__ == "__main__":
    #test_audio()
    test_cpu()
    test_disk()
    test_env()
    test_fio()
    test_iperf()
    test_irqbalance()
    test_kernel_mem()
    test_limits()
    test_my_cnf()
    test_net()
    test_nginx_conf()
    test_scheduler()
    #test_scsi_host()
    test_sysbench()
    test_sysctl()
    test_sysfs()
    test_systemd()
    test_vm()
    test_wrk()